import { checkWxLogin, fomatData } from '../../api/server';
import { apiService } from '../../api/apiService';
import { LoginSetup } from '@/setup/login/LoginSetup';
import { useStore } from 'vuex';
import Cookies from 'js-cookie';
import { selfI18n } from '@/i18n';
export function StarterSetup () {
    const { setUserInfo } = LoginSetup();
    const store = useStore();
    const getAndSaveDeviceParamFormatData = () => {
        apiService({
            api: fomatData,
            param: {},
            success: (data) => {
                // const formatTime = JSON.stringify(data.value);
                // sessionStorage.formatTime = formatTime;
                const formatData = data.value;
                const formatMap = {};
                if (formatData && formatData.length > 0) {
                    formatData.forEach(item => {
                        formatMap[item.key] = item;
                    });
                }
                const formatTime = JSON.stringify(formatMap);

                sessionStorage.formatTime = formatTime;
            }
        });
    };
    const checkLogin = (openid, loginfrom) => {
        return new Promise((resolve, reject) => {
            apiService({
                api: checkWxLogin,
                param: { openid, loginfrom },
                success: (data) => {
                    setUserInfo(data.value, data.token);
                    resolve();
                },
                fail: () => {
                    setUserInfo({ openid });
                    reject(new Error(selfI18n('wp_User_is_not_logged_in')));
                },
                error: () => {
                    setUserInfo({ openid });
                    reject(new Error(selfI18n('wp_User_is_not_logged_in')));
                }
            });
        });
    };
    const checkLoginByUsername = (username, loginfrom) => {
        return new Promise((resolve, reject) => {
            apiService({
                api: checkWxLogin,
                param: { username, loginfrom },
                success: (data) => {
                    setUserInfo(data.value, data.token);
                    resolve();
                },
                fail: () => {
                    reject(new Error(selfI18n('wp_User_is_not_logged_in')));
                }
            });
        });
    };
    const getUserRolesFromCookies = () => {
        const roles_cookie = Cookies.get('roles');
        let roles;
        if (roles_cookie) {
            roles = roles_cookie.split(',');
            store.commit('SET_USER_ROLES', roles);
        }
    };

    return {
        getUserRolesFromCookies,
        checkLogin,
        checkLoginByUsername,
        getAndSaveDeviceParamFormatData
    };
}
